package com.kinghood.productcenter.common.utils;

import com.kinghood.infrastructure.model.KingHoodExceptionUtil;
import com.kinghood.productcenter.common.properties.BaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2024-01-29 11:10
 **/
@Slf4j
@Component
public class WebClientRpc {

    @Resource
    private BaseProperties baseProperties;
    private WebClient restCloud;
    private ThreadLocal<WebClient> restClient = new ThreadLocal<>();

    @PostConstruct
    public void init(){
        restCloud = WebClient.builder()
                .baseUrl(baseProperties.getRestCloudBaseUrl())
                .build();
    }

    public WebClient getRestCloud() {
        return restCloud;
    }

    public WebClientRpc restCloud() {
        restClient.set(restCloud);
        return this;
    }

    /**
     * 携带body的post请求
     *
     * @param uri 请求的uri
     * @param t   请求的body
     * @param c   返回的类型
     * @return
     * @author zfj
     * @date 2024/1/29
     */
    public <T> Object post(String uri, T t, Class c) {
        WebClient webClient = restClient.get();
        KingHoodExceptionUtil.isNull(webClient, "先执行restClient初始化方法");

        Mono mono = webClient.post()
                .uri(uri)
                .bodyValue(t)
                .exchange()
//                .retry()
                .flatMap(response -> {
                    HttpStatus status = response.statusCode();
                    if (status.is2xxSuccessful()) {
                        return response.bodyToMono(c);
                    } else {
                        return response.createException().flatMap(Mono::error);
                    }
                });
        return mono.block();
    }


    /**
     * body不返回，直接消费
     * 可以使用subscribe的返回参数Disposable执行订阅停止和释放资源
     */
    public <T> void post(String uri, T t) {
        WebClient webClient = restClient.get();
        KingHoodExceptionUtil.isNull(webClient, "先执行restClient初始化方法");

        webClient.post()
                .uri(uri)
                .bodyValue(t)
                .exchange()
                .flatMap(response -> {
                    HttpStatus status = response.statusCode();
                    if (status.is2xxSuccessful()) {
                        return response.bodyToMono(String.class);
                    } else {
                        return response.createException().flatMap(Mono::error);
                    }
                })
                .subscribe(responseBody -> {
                    log.info("{}", responseBody);
                }, error -> {
                    log.error("发生异常：", error);
                    KingHoodExceptionUtil.throwException("请求发生异常：" + error.getMessage());
                });
    }


}
